<template>
  <div class="Map">
    <div>
      <el-drawer
        title="使用指南"
        :visible.sync="drawer"
        direction="ltr"
        :with-header="false">
         <el-collapse v-model="activeName" accordion>
            <el-collapse-item title="点击上传" name="1">
              <div>考虑到批量读取数据的原因，支持上传的文件类型为xlsx和xls；</div>
              <div>由于技术水平的限制，希望您不要上传重复的数据，上传的数据内容也要严格限制（以便于我们更好的为您展示数据），具体如下所示；</div>
              <el-tag type="info">姓名</el-tag>
              <el-tag type="info">性别</el-tag>
              <el-tag type="info">毕业年级</el-tag>
              <el-tag type="info">电话</el-tag>
              <el-tag type="info">学校</el-tag>
              <el-tag type="info">省份</el-tag>
              <el-tag type="info">市区</el-tag>
            </el-collapse-item>
            <el-collapse-item title="下载模板" name="2">
              <div>为了方便使用者更加方便地上传数据并展示在地图上，我们提供了一键下载模板的功能，关于内容输入有一定限制，我们希望您了解；</div>
              <div>毕业年级，我们希望您输入的数字（严格按照这种格式），例如18；</div>
              <div>省份，我们希望您输入完整的内容，例如北京市、陕西省、西藏自治区或者香港特别行政区；</div>
              <div>市区，我们希望您输入大学所在的市，例如北京大学在北京市、新疆大学在乌鲁木齐或者香港大学在香港特别行政区；</div>
            </el-collapse-item>
            <el-collapse-item title="地区搜索" name="3">
              <div>为了提供更好地体验感，我们提供了搜索的功能；</div>
              <div>搜索支持输入，也有输入联想功能。</div>
            </el-collapse-item>
            <el-collapse-item title="意见反馈" name="4">
              <div>为了提供给使用者反馈的平台，我们借助腾讯兔小巢，实现了意见反馈；</div>
              <div>点击图标就可进入相关页面，您可以畅所欲言，反馈您的想法或者意见给我们，欢迎交流。</div>
            </el-collapse-item>
            <el-collapse-item title="搜索切换" name="5">
              <div>为了提供给使用者更加丰富的体验感，我们提供了两种搜索方式；</div>
              <div>一种是按照省市特别行政区搜索，另一种为按照学生姓名进行搜索，我们同时提供了相关查找列表，方便具体查找。</div>
            </el-collapse-item>
          </el-collapse>
      </el-drawer>
    </div>
    <baidu-map class="map" :center="{ lng, lat }" :zoom="zoom" @ready="handler">
      <!--缩放-->
      <bm-navigation anchor="BMAP_ANCHOR_TOP_LEFT"></bm-navigation>
      <!--定位-->
      <bm-geolocation
        anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
        :showAddressBar="true"
        :autoLocation="true"
      ></bm-geolocation>
      <!--点-->
      <div v-for="(item,index) in college" :key="index">
        <!-- tip：引入小图标加入require，而且size的值必须和iconfont获取的图片长宽一致 -->
        <bm-marker  
          :position="{lng:item.lng,lat:item.lat}"
          :dragging="dragging"
          animation="BMAP_ANIMATION_DROP"
          @click="infoWindow(item)"

        >

          <!--提示信息-->
          <bm-info-window
            :show="item.showFlag"
            :title="item.university"
            :position="{lng:item.lng,lat:item.lat}"
            @open="infoWindowOpen(item)"
            @close="infoWindowClose(item)"
            style="font-size: 14px"
          >
              <el-table
                ref="myTable"
                :data="item.info.filter(data => !flag || data.name.toLowerCase().includes(flag.toLowerCase()))"
                max-height="260"
                stripe
                border
                :default-sort = "{prop: 'graduate', order: 'descending'}"
                style="width: 100%">
                <el-table-column
                  prop="name"
                  label="姓名"
                  width="80">
                </el-table-column>
                <el-table-column
                  prop="sex"
                  label="性别"
                  width="80">
                </el-table-column>
                <el-table-column
                  width="240">
                    <template slot="header" slot-scope="{}">
                      <el-input
                        v-model="flag"
                        size="mini"
                        @input=change($event)
                        placeholder="输入学生姓名搜索"/>
                    </template>
                  <el-table-column
                     prop="graduate"
                     label="毕业年级"
                     width="120">
                  </el-table-column>
                  <el-table-column
                    prop="phone"
                    label="联系方式"
                    width="120">
                  </el-table-column>
                </el-table-column>
              </el-table>
          </bm-info-window>

        </bm-marker>
      </div>
    </baidu-map>
  </div>
</template>

<script>
import axios from "axios";
import bus from '../utils/eventBus';
axios.defaults.headers.post["Content-Type"] = "application/json";

export default {
  name: "College-Map",
  data() {
    return {
      drawer: false,  //组件抽屉是否打开
      activeName:'1',  //展开的折叠面板
      lng: 116.399855,
      lat: 39.882858,
      zoom: 12.8,
      dragging: false,
      college: [],
      info:{},
      searchByProvince:'',
      searchByName:[],
      flag:'',   //搜索的内容
    };
  },
  created() {
    this.getCollege();
    this.getLL();
  },

  mounted(){
    bus.$on('search',data => {
      console.log(data);
      this.searchByProvince = data;
    })

    bus.$on('searchByName',data => {
      this.searchByName = data['info'];
      console.log(this.searchByName);
    })

    bus.$on('drawer',data => {
      this.drawer = data;
    })
  },
 
  watch:{
    searchByProvince(newName,oldName){
        let email = localStorage.getItem('email');
        this.$axios.get(`/bbb/geocoding/v3/?address=${newName}&output=json&ak=1weYccRbkZdkmWxZL6wDuuj04TzYt7Go`).then(res => {
          console.log(res);
          if(newName == '香港特别行政区'){
            this.lng = 114.194408;
            this.lat = 22.348008;
          }
          else if(newName == '青海省'){
            this.lng = 101.783582;
            this.lat = 36.623666;
          }
          else{
            this.lng = res.data.result.location.lng;
            this.lat = res.data.result.location.lat;
          }
          
        },err => {
          console.log('Error: ' + err);
        })
        
        this.college = [];

        this.$axios.get(`http://119.91.81.28:1337/students?province=${newName}&createdBy=${email}`).then(res => {
            
            console.log(res);
            let m = new Map();
            
            res.data.forEach((item) => {

               if(m.has(item.college)){
                 let arr = [];
                 arr.push({
                  name:item.name,
                  sex:item.sex,
                  graduate:item.graduate,
                  phone:item.phone,
                  pro:item.province,
                  region:item.downtown,
                  university:item.college,
                 })

                 m.set(item.college,arr.concat(m.get(item.college)));
               }
               else{
                 let arr = [];
                 arr.push({
                  name:item.name,
                  sex:item.sex,
                  graduate:item.graduate,
                  phone:item.phone,
                  pro:item.province,
                  region:item.downtown,
                  university:item.college,
                 })

                 m.set(item.college,arr);
               }
            })

            for(let [key,value] of m.entries()){
               let temp = value[0].region;

               let array = new Map();

               this.$axios.get('http://119.91.81.28:1337/colleges').then(res => {
                 console.log(res.data);
                 res.data.forEach((item) => {
                    array.set(item.university,[item.lng,item.lat])
                 })

                 let keys = [...array.keys()];

                 if(keys.includes(key)){
                    let [a1,a2] = array.get(key);
                    this.college.push(
                        Object.assign({}, {
                          info:value,
                          university:key,
                          lng:a1,
                          lat:a2,
                          showFlag:false,
                        })
                    );
                 }
                 else{
                   this.$axios.get(`/bbb/place/v2/suggestion?query=${key}&region=${temp}&city_limit=true&output=json&ak=1weYccRbkZdkmWxZL6wDuuj04TzYt7Go`).then(res => {
                    console.log(res);
                    let result = res.data.result;
                    
                    for(let i = 0;i < result.length;i++){
                        let item = result[i];
                        if(item.tag == '高校' || item.tag == '大学'){
                          this.college.push(
                              Object.assign({}, {
                                info:value,
                                university:key,
                                lng:item.location.lng,
                                lat:item.location.lat,
                                showFlag:false,
                              })
                          );

                          let object = { university:key,lng:String(item.location.lng),lat:String(item.location.lat)}

                          this.$axios.post('http://119.91.81.28:1337/colleges',JSON.stringify(object)).then(res => {
                            console.log(res);
                          })

                          break;
                        }
                    
                      }
                    })

                 }
               })

              
            }
           
        });

        console.log(this.college);      
    },

    searchByName(newValue,oldValue){
       let arr = [];
       let studentInfo = {};
       let infomation = ['name','sex','graduate','phone'];
       for(let key in newValue){
         if(infomation.includes(key)){
            studentInfo[key] = newValue[key];
         }
         else if(key == 'province'){
            studentInfo['pro'] = newValue[key];
         }
         else if(key == 'downtown'){
            studentInfo['region'] = newValue[key];
         }
         else if(key == 'college'){
            studentInfo['university'] = newValue[key];
         }
         else{
           continue;
         }
       }
       arr[0] = studentInfo;
       let town = newValue.downtown;
       let newName = newValue.province;
       let uni = newValue.college;
       this.$axios.get(`/bbb/geocoding/v3/?address=${town}&output=json&ak=1weYccRbkZdkmWxZL6wDuuj04TzYt7Go`).then(res => {
          console.log(res);
          if(newName == '香港特别行政区'){
            this.lng = 114.194408;
            this.lat = 22.348008;
          }
          else if(newName == '青海省'){
            this.lng = 101.783582;
            this.lat = 36.623666;
          }
          else{
            this.lng = res.data.result.location.lng;
            this.lat = res.data.result.location.lat;
          }

          this.college = [];

          this.$axios.get(`http://119.91.81.28:1337/colleges?university=${uni}`).then(response => {
              console.log(response);
              let temp = response.data[0];
              if(!temp){
                 this.$axios.get(`/bbb/place/v2/suggestion?query=${uni}&region=${newValue['downtown']}&city_limit=true&output=json&ak=1weYccRbkZdkmWxZL6wDuuj04TzYt7Go`).then(resp => {
                    console.log(resp);
                    let result = resp.data.result;
                    
                    for(let i = 0;i < result.length;i++){
                        let item = result[i];
                        if(item.tag == '高校' || item.tag == '大学'){
                          this.college.push(
                              Object.assign({}, {
                                info:arr,
                                university:uni,
                                lng:item.location.lng,
                                lat:item.location.lat,
                                showFlag:false,
                              })
                          );

                          let object = { university:uni,lng:String(item.location.lng),lat:String(item.location.lat)}

                          this.$axios.post('http://119.91.81.28:1337/colleges',JSON.stringify(object)).then(res => {
                            console.log(res);
                          })

                          break;
                        }
                    
                      }
                 })
              }
              else{
                this.college.push({
                  info:arr,
                  university:temp.university,
                  lng:temp.lng,
                  lat:temp.lat,
                  showFlag:false
                })
              }

              console.log(this.college);
          },error => {
            console.log(error);
          })
          
        },err => {
          console.log('Error: ' + err);
      })
    }
  },
  methods: {
    handler({ BMap, map }) {
      //console.log(BMap, map);
      // 鼠标缩放
      map.enableScrollWheelZoom(true);
      // 点击事件获取经纬度
      map.addEventListener("click", function(e) {
        console.log(e.point.lng, e.point.lat);
      });
    },

    getLL() {    // 获取当前所在地区经纬度
       let ip = returnCitySN["cip"];
      this.$axios
        .get("/bbb/location/ip?ak=1weYccRbkZdkmWxZL6wDuuj04TzYt7Go&ip="+ip)
        .then(resp => {
          this.$axios
            .get(
              "/bbb/geocoding/v3/?address=" +
                resp.data.content.address +
                "&output=json&ak=1weYccRbkZdkmWxZL6wDuuj04TzYt7Go"
            )
            .then(
              res => {
                let that = this;
                console.log(res);
                that.lng = res.data.result.location.lng;
                that.lat = res.data.result.location.lat;
              },
              err => {
                console.log("Error: " + err);
              }
            );
        });
    },

    getCollege() {     // 获取当前地区的所有大学
        let email = localStorage.getItem('email');
         let ip = returnCitySN["cip"];
        this.$axios.get("/bbb/location/ip?ak=1weYccRbkZdkmWxZL6wDuuj04TzYt7Go&ip="+ip).then(resp => {
          this.$axios.get(`http://119.91.81.28:1337/students?province=${resp.data.content.address_detail.province}&createdBy=${email}`).then(res => {
            
            console.log(res);
            let m = new Map();
            
            res.data.forEach((item) => {

               if(m.has(item.college)){
                 let arr = [];
                 arr.push({
                  name:item.name,
                  sex:item.sex,
                  graduate:item.graduate,
                  phone:item.phone,
                  pro:item.province,
                  region:item.downtown,
                  university:item.college,
                 })

                 m.set(item.college,arr.concat(m.get(item.college)));
               }
               else{
                 let arr = [];
                 arr.push({
                  name:item.name,
                  sex:item.sex,
                  graduate:item.graduate,
                  phone:item.phone,
                  pro:item.province,
                  region:item.downtown,
                  university:item.college,
                 })

                 m.set(item.college,arr);
               }
            })

             for(let [key,value] of m.entries()){
               let temp = value[0].region;

               let array = new Map();

               this.$axios.get('http://119.91.81.28:1337/colleges').then(res => {
                 console.log(res.data);
                 res.data.forEach((item) => {
                    array.set(item.university,[item.lng,item.lat])
                 })

                 let keys = [...array.keys()];

                 if(keys.includes(key)){
                    let [a1,a2] = array.get(key);
                    this.college.push(
                        Object.assign({}, {
                          info:value,
                          university:key,
                          lng:a1,
                          lat:a2,
                          showFlag:false,
                        })
                    );
                 }
                 else{
                   this.$axios.get(`/bbb/place/v2/suggestion?query=${key}&region=${temp}&city_limit=true&output=json&ak=1weYccRbkZdkmWxZL6wDuuj04TzYt7Go`).then(res => {
                    console.log(res);
                    let result = res.data.result;
                    
                    for(let i = 0;i < result.length;i++){
                        let item = result[i];
                        if(item.tag == '高校' || item.tag == '大学'){
                          this.college.push(
                              Object.assign({}, {
                                info:value,
                                university:key,
                                lng:item.location.lng,
                                lat:item.location.lat,
                                showFlag:false,
                              })
                          );

                          let object = { university:key,lng:String(item.location.lng),lat:String(item.location.lat)}

                          this.$axios.post('http://119.91.81.28:1337/colleges',JSON.stringify(object)).then(res => {
                            console.log(res);
                          })

                          break;
                        }
                    
                      }
                    })

                 }
               })


             }
           
        });
        })


        console.log(this.college);
       
    },

    infoWindow(item){
       item.showFlag = true;
       console.log(item);
    },

    infoWindowOpen(item) {
      item.showFlag = true;
    },

    infoWindowClose(item) {
      item.showFlag = false;
      this.flag = "";   // 此处修复了每次点开弹窗输入框都有数据的bug！！！
    },

    change(e){
      this.$forceUpdate();
    }
  }
}
</script>

<style>
.Map {
  width: 100%;
  flex: 1;
}
.map {
  width: 100%;
  height: 85vh;
}
/* 去掉百度地图的小图标 */
.anchorBL {
  display: none;
}
.el-table{
  width:99.9% !important;
}
</style>
